package cn.xfdzx.android.apps.shop.activity.remake;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.GridImageSelAdapter;
import cn.xfdzx.android.apps.shop.adapter.remake.OrderRemakeGoodsMarketAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AfterServiceUpLoadMoreImgBean;
import cn.xfdzx.android.apps.shop.bean.AfterServiceUpLoadSingImgBean;
import cn.xfdzx.android.apps.shop.bean.DissatisfiedReasonBean;
import cn.xfdzx.android.apps.shop.bean.MyRemakeListMarketBean;
import cn.xfdzx.android.apps.shop.bean.MyRemakeListRetailBean;
import cn.xfdzx.android.apps.shop.bean.OrderListBeen;
import cn.xfdzx.android.apps.shop.bean.PeiSongBeen;
import cn.xfdzx.android.apps.shop.bean.RemakeGoodsBean;
import cn.xfdzx.android.apps.shop.bean.ShopRemakeListMarketBean;
import cn.xfdzx.android.apps.shop.bean.ShopRemakeListRetailBean;
import cn.xfdzx.android.apps.shop.contract.OrderRemakeContract;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMyOrderMessage;
import cn.xfdzx.android.apps.shop.presenter.OrderRemakePresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.FileUtils;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.SoftKeyBoardListener;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/*
/* 批发订单评价页面
 */
public class OrderRemakeMarketActivity extends BaseMvpActivity<OrderRemakePresenter>implements OrderRemakeContract.View {
    @BindView(R.id.iv_back)
    ImageView ivBack;      //标题栏-左边按钮
    @BindView(R.id.ll_state)
    LinearLayout llState;   //
    @BindView(R.id.star01_zl)
    ImageView star01_zl;   //质量评分星星
    @BindView(R.id.star02_zl)
    ImageView star02_zl;   //质量评分星星
    @BindView(R.id.star03_zl)
    ImageView star03_zl;   //质量评分星星
    @BindView(R.id.star04_zl)
    ImageView star04_zl;   //质量评分星星
    @BindView(R.id.star05_zl)
    ImageView star05_zl;   //质量评分星星
    @BindView(R.id.star01_bz)
    ImageView star01_bz;   //包装评分星星
    @BindView(R.id.star02_bz)
    ImageView star02_bz;   //包装评分星星
    @BindView(R.id.star03_bz)
    ImageView star03_bz;   //包装评分星星
    @BindView(R.id.star04_bz)
    ImageView star04_bz;   //包装评分星星
    @BindView(R.id.star05_bz)
    ImageView star05_bz;   //包装评分星星
    @BindView(R.id.tv_zt_state_zl)
    TextView tv_zt_state_zl;   //质量满意度
    @BindView(R.id.tv_zt_state_bz)
    TextView tv_zt_state_bz;   //包装满意度
    @BindView(R.id.recycler_goods)
    RecyclerView recycler_goods;   //商品列表
    @BindView(R.id.tv_submit)
    TextView tv_submit;   //提交评价按钮
    @BindView(R.id.rl_top)
    RelativeLayout rl_top;   //商品列表外部布局，用于监听软键盘设置焦点问题
    @BindView(R.id.tv_goodsnum)
    TextView tv_goodsnum;   //共计几件商品可评价

    private RelativeLayout.LayoutParams item_bar;
    private OrderListBeen.DataBean dataBean;
    private List<OrderListBeen.DataBean.CartInfoBean> cartInfo;//商品列表
    private List<OrderListBeen.DataBean.CartInfoBean> cartInfoSave = new ArrayList<>();////用于显示或者隐藏更多列表
    private OrderRemakeGoodsMarketAdapter remakeGoodsAdapter;//商品列表适配器
    private int all;//总体评价(如果是批发端为货品评价)
    private int quality;//服务态度评价(如果是批发端为服务态度的评价)
    private int packing;//物流服务评价(如果是批发端为物流服务的评价)
    private List<RemakeGoodsBean> remakeGoodsBeanList = new ArrayList<>();//上传的评价商品列表
    private String pageType = "3";//页面类型，1零售配送，2零售自提，3批发
    private String pageposition;//区分fragment页面跳转，评价完成刷新页面
    //图片上传相关
    private GridImageSelAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();//图片选择结果列表
    private boolean mode = true;//默认相册选择
    private List<MultipartBody.Part> upfiles = new ArrayList<>();//多图上传文件
    private String imgPathJson;//上传图片路径json
    //图片上传相关

    private int currentPosition;//图片上传当前商品角标
    private boolean isOpen;//是否展开
    @Override
    public int getLayoutId() {
        return R.layout.activity_remake_market;
    }

    @Override
    public void initView() {
        initHigh();
        dataBean = (OrderListBeen.DataBean) getIntent().getSerializableExtra("data");
        pageposition = getIntent().getStringExtra("pageposition");
        cartInfo = dataBean.getCartInfo();
        cartInfoSave.add(cartInfo.get(0));

        mPresenter = new OrderRemakePresenter();
        mPresenter.attachView(this);

        mPresenter.getDissatisfied();//请求不满意原因
        mPresenter.getPeisongInfo(dataBean.getOrder_id());//请求配送员信息

        initRecycle();
        initListener();
        initDate();
    }

    /*初始化页面数据显示*/
    private void initDate() {
        tv_goodsnum.setText("共"+dataBean.getCartInfo().size()+"件商品可评价");

        tv_goodsnum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cartInfo.size()==1){
                    return;
                }
                isOpen = !isOpen;
                if (isOpen){
                    Drawable nav_up1 = getResources().getDrawable(R.drawable.icon_location_on);
                    nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
                    tv_goodsnum.setCompoundDrawables(null, null, nav_up1, null);
                    remakeGoodsAdapter.is_open = true;
                    remakeGoodsAdapter.notifyDataSetChanged();
                }else {
                    Drawable nav_up1 = getResources().getDrawable(R.drawable.icon_location_down);
                    nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
                    tv_goodsnum.setCompoundDrawables(null, null, nav_up1, null);
                    remakeGoodsAdapter.is_open = false;
                    remakeGoodsAdapter.notifyDataSetChanged();
                }
            }
        });


        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(OrderRemakeMarketActivity.this, PictureConfig.TYPE_IMAGE);
                } else {
                    Toast.makeText(OrderRemakeMarketActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
        llState.setBackgroundColor(getResources().getColor(R.color.color_F2F2F2));

    }

    private void initRecycle() {

        remakeGoodsAdapter = new OrderRemakeGoodsMarketAdapter(cartInfo,cartInfoSave);
        recycler_goods.setLayoutManager(new LinearLayoutManager(this));
        recycler_goods.setAdapter(remakeGoodsAdapter);
        Log.e("tv_goodsnum",cartInfo.size()+"---适配器中大小");
       // remakeGoodsAdapter.refreshDatas(cartInfoSave);
        /**图片选择回调*/
        remakeGoodsAdapter.setItemImgSelListener(new OrderRemakeGoodsMarketAdapter.OnItemImgSelListener() {
            @Override
            public void onItemImgSelClick(int position, OrderListBeen.DataBean.CartInfoBean date) {
                OrderRemakeMarketActivity.this.currentPosition = position;
                showPublishDialog();
                Log.e("currentPosition",cartInfo.get(position).getStarNum()+"星星数量");

            }

        });

    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void finishLoadMore() {

    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    /**上传多张回调*/
    @Override
    public void onUploadMoreImgSuccess(AfterServiceUpLoadMoreImgBean bean) {
        hideLoading();
        if (bean.getErrno().equals("200")){
            requestRemakeMoreImage(bean);
        }else {
            ToastUtils.s(this,bean.getMessage());
        }
    }

    /**
     * 上传多图完成,请求评论接口
     * */
    private void requestRemakeMoreImage(AfterServiceUpLoadMoreImgBean bean) {
        imgPathJson = new Gson().toJson(bean.getData().getSrc());
        cartInfo.get(currentPosition).setUpLoadImagPath(imgPathJson);
        Log.e("imgPathJson",imgPathJson+"---");
    }

    /**上传单张回调*/
    @Override
    public void onUploadSingImgSuccess(AfterServiceUpLoadSingImgBean bean) {
        hideLoading();
        if (bean.getErrno().equals("200")){
            requestRemakeSingImage(bean);
        }else {
            ToastUtils.s(this,bean.getMessage());
        }
    }

    /**
     * 上传单图完成,请求评论接口
     * */
    private void requestRemakeSingImage(AfterServiceUpLoadSingImgBean bean) {
        imgPathJson = "["+new Gson().toJson(bean.getData().getSrc())+"]";
        cartInfo.get(currentPosition).setUpLoadImagPath(imgPathJson);
        Log.e("imgPathJson",imgPathJson+"---");
    }

    /**请求评价*/
    private void requestRemake() {
        Map<String,Object> map = new HashMap<>();
        map.put("orderId",dataBean.getOrder_id());
        map.put("storeId",dataBean.getStore().getId());
        map.put("quality",quality);
        map.put("packing",packing);
        map.put("goods",new Gson().toJson(remakeGoodsBeanList));

        mPresenter.getRemakeMarket(map);
    }

    private void initListener() {
        setSoftKeyBoardListener();
//        ed_des.addTextChangedListener(textWatcher);
//        //Edittext通知父控件自己处理自己的滑动事件
//        ed_des.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (v.getId() == R.id.ed_des && canVerticalScroll(ed_des)) {
//                    v.getParent().requestDisallowInterceptTouchEvent(true);
//                    if (event.getAction() == MotionEvent.ACTION_UP) {
//                        v.getParent().requestDisallowInterceptTouchEvent(false);
//                    }
//                }
//                return false;
//            }
//        });
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param //editText需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText contentEt) {
        //滚动的距离
        int scrollY = contentEt.getScrollY();
        //控件内容的总高度
        int scrollRange = contentEt.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = contentEt.getHeight() - contentEt.getCompoundPaddingTop() - contentEt.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }
        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    @Override
    public void onGetDissatisfiedSuccess(DissatisfiedReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetRemakeRetailSuccess(DissatisfiedReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getPeisongInfoSuccess(PeiSongBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetRemakeMarketSuccess(DissatisfiedReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Intent intent = new Intent(this, OrderRemakeFinishActivity.class);
            intent.putExtra("pageType",pageType);
            intent.putExtra("shopimg",dataBean.getStore().getLogo());
            startActivity(intent);
            EventBus.getDefault().post(new UpdateMyOrderMessage(pageposition));
            finish();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetMyRemakeListRetailSuccess(MyRemakeListRetailBean bean) {

    }

    @Override
    public void onGetMyRemakeListMarketSuccess(MyRemakeListMarketBean bean) {

    }

    @Override
    public void onGetDeleteRemakeSuccess(MyRemakeListMarketBean bean) {

    }

    @Override
    public void onGetShopRemakeRetailSuccess(ShopRemakeListRetailBean bean) {

    }

    @Override
    public void onGetShopRemakeMarketSuccess(ShopRemakeListMarketBean bean) {

    }

    @OnClick({R.id.iv_back,R.id.tv_submit,
            R.id.star01_zl,R.id.star02_zl,R.id.star03_zl,R.id.star04_zl,R.id.star05_zl,
            R.id.star01_bz,R.id.star02_bz,R.id.star03_bz,R.id.star04_bz,R.id.star05_bz,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;
            case R.id.tv_submit:    //提交评价按钮
                remakeGoodsBeanList.clear();
                if (quality==0){
                    Utils.toastMessage(this,"请给物流服务评分");
                    return;
                }
                if (packing==0){
                    Utils.toastMessage(this,"请给服务态度评分");
                    return;
                }

                for (int i = 0; i < cartInfo.size(); i++) {
                    if (cartInfo.get(i).getStarNum()== 0){//批发商品不选默认5星
                        remakeGoodsBeanList.add(new RemakeGoodsBean(cartInfo.get(i).getProduct_id()+"",
                                5,cartInfo.get(i).getRemakeContent(),cartInfo.get(i).getUpLoadImagPath()));
                    }else {
                        remakeGoodsBeanList.add(new RemakeGoodsBean(cartInfo.get(i).getProduct_id()+"",
                                cartInfo.get(i).getStarNum(),cartInfo.get(i).getRemakeContent(),cartInfo.get(i).getUpLoadImagPath()));
                    }
                }
                requestRemake();

                break;
            case R.id.star01_zl:    //服务态度星星1
                quality = 1;
                Log.e("star",quality+"-------");
                setStarLight(star01_zl,star02_zl,star03_zl,star04_zl,star05_zl,"1",tv_zt_state_zl);
                break;
            case R.id.star02_zl:    //服务态度星星2
                quality = 2;
                setStarLight(star01_zl,star02_zl,star03_zl,star04_zl,star05_zl,"2",tv_zt_state_zl);
                Log.e("star",quality+"-------");
                break;
            case R.id.star03_zl:    //服务态度星星3
                quality = 3;
                setStarLight(star01_zl,star02_zl,star03_zl,star04_zl,star05_zl,"3",tv_zt_state_zl);
                Log.e("star",quality+"-------");
                break;
            case R.id.star04_zl:    //服务态度星星4
                quality = 4;
                setStarLight(star01_zl,star02_zl,star03_zl,star04_zl,star05_zl,"4",tv_zt_state_zl);
                Log.e("star",quality+"-------");
                break;
            case R.id.star05_zl:    //服务态度星星5
                quality = 5;
                setStarLight(star01_zl,star02_zl,star03_zl,star04_zl,star05_zl,"5",tv_zt_state_zl);
                break;
            case R.id.star01_bz:    //物流星星1
                packing = 1;
                setStarLight(star01_bz,star02_bz,star03_bz,star04_bz,star05_bz,"1",tv_zt_state_bz);
                break;
            case R.id.star02_bz:    //物流星星2
                packing = 2;
                setStarLight(star01_bz,star02_bz,star03_bz,star04_bz,star05_bz,"2",tv_zt_state_bz);
                break;
            case R.id.star03_bz:    //物流星星3
                packing = 3;
                setStarLight(star01_bz,star02_bz,star03_bz,star04_bz,star05_bz,"3",tv_zt_state_bz);
                break;
            case R.id.star04_bz:    //物流星星4
                packing = 4;
                setStarLight(star01_bz,star02_bz,star03_bz,star04_bz,star05_bz,"4",tv_zt_state_bz);
                break;
            case R.id.star05_bz:    //物流星星5
                packing = 5;
                setStarLight(star01_bz,star02_bz,star03_bz,star04_bz,star05_bz,"5",tv_zt_state_bz);
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**设置星星点亮的方法*/
    private void setStarLight(ImageView img_star1,ImageView img_star2,ImageView img_star3,
                              ImageView img_star4,ImageView img_star5,String star,TextView tv_zt_state) {
        switch (star){
            case "1":

                clearStarLight(img_star1,img_star2,img_star3,img_star4,img_star5);
                img_star1.setImageResource(R.drawable.ic_staryellow);

                Animation ani = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star1.startAnimation(ani);//開始动画

                tv_zt_state.setVisibility(View.VISIBLE);
                tv_zt_state.setText("非常差");
                break;
            case "2":
                clearStarLight(img_star1,img_star2,img_star3,img_star4,img_star5);
                img_star1.setImageResource(R.drawable.ic_staryellow);
                img_star2.setImageResource(R.drawable.ic_staryellow);

                Animation anim1 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star1.startAnimation(anim1);//開始动画
                Animation anim2 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star2.startAnimation(anim2);//開始动画

                tv_zt_state.setVisibility(View.VISIBLE);
                tv_zt_state.setText("差");
                break;
            case "3":
                clearStarLight(img_star1,img_star2,img_star3,img_star4,img_star5);
                img_star1.setImageResource(R.drawable.ic_staryellow);
                img_star2.setImageResource(R.drawable.ic_staryellow);
                img_star3.setImageResource(R.drawable.ic_staryellow);

                Animation anima1 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star1.startAnimation(anima1);//開始动画
                Animation anima2 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star2.startAnimation(anima2);//開始动画
                Animation anima3 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star3.startAnimation(anima3);//開始动画

                tv_zt_state.setVisibility(View.VISIBLE);
                tv_zt_state.setText("一般");
                break;
            case "4":
                clearStarLight(img_star1,img_star2,img_star3,img_star4,img_star5);
                img_star1.setImageResource(R.drawable.ic_staryellow);
                img_star2.setImageResource(R.drawable.ic_staryellow);
                img_star3.setImageResource(R.drawable.ic_staryellow);
                img_star4.setImageResource(R.drawable.ic_staryellow);

                Animation animation1 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star1.startAnimation(animation1);//開始动画
                Animation animation2 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star2.startAnimation(animation2);//開始动画
                Animation animation3 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star3.startAnimation(animation3);//開始动画
                Animation animation4 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star4.startAnimation(animation4);//開始动画

                tv_zt_state.setVisibility(View.VISIBLE);
                tv_zt_state.setText("满意");
                break;
            case "5":
                img_star1.setImageResource(R.drawable.ic_staryellow);
                img_star2.setImageResource(R.drawable.ic_staryellow);
                img_star3.setImageResource(R.drawable.ic_staryellow);
                img_star4.setImageResource(R.drawable.ic_staryellow);
                img_star5.setImageResource(R.drawable.ic_staryellow);

                Animation animations1 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star1.startAnimation(animations1);//開始动画
                Animation animations2 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star2.startAnimation(animations2);//開始动画
                Animation animations3 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star3.startAnimation(animations3);//開始动画
                Animation animations4 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star4.startAnimation(animations4);//開始动画
                Animation animations5 = AnimationUtils.loadAnimation(this, R.anim.anim_star_scale);
                img_star5.startAnimation(animations5);//開始动画

                tv_zt_state.setVisibility(View.VISIBLE);
                tv_zt_state.setText("非常满意");
                break;
            default:
                clearStarLight(img_star1,img_star2,img_star3,img_star4,img_star5);
                img_star1.setImageResource(R.drawable.ic_staryellow);
                break;
        }
        checkBtnState();//检查提交按钮状态
    }

    private void clearStarLight(ImageView img_star1,ImageView img_star2,ImageView img_star3,ImageView img_star4,ImageView img_star5) {
        img_star1.setImageResource(R.drawable.ic_stargray);
        img_star2.setImageResource(R.drawable.ic_stargray);
        img_star3.setImageResource(R.drawable.ic_stargray);
        img_star4.setImageResource(R.drawable.ic_stargray);
        img_star5.setImageResource(R.drawable.ic_stargray);
    }

    /**上传图片*/
    private void upload() {
        upfiles.clear();
        for (LocalMedia media : selectList) {
            Log.i("图片-----》", media.getPath()+ "-----"+ media.position);
            if (EmptyUtil.isNotEmpty(media.getPath())){
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(media.getCompressPath());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        Bitmap bitmap  = BitmapFactory.decodeStream(fis);
                        File file = FileUtils.getFile(bitmap,"remakeImg"+media.position);

                        uploadImg(file,"remakeImg"+ media.position);
                        if(null != fis){
                            fis.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //Log.e("upfiles","upfiles上传图片"+upfiles.size());
        try{
            //服务器单张和多张返回类型不同，调用不同方法
            if (upfiles.size()>1){
                mPresenter.uploadMoreImg(upfiles);
            }else {
                mPresenter.uploadSingImg(upfiles);
            }
            showLoading();
        }catch (Exception e){
            Log.e("Exception",e.toString());
        }
    }

    private GridImageSelAdapter.onAddPicClickListener onAddPicClickListener = new GridImageSelAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            showPublishDialog();
//            if (mode) {
//                // 进入相册 以下是例子：不需要的api可以不写
//                getBitmapFromGallery();
//            } else {
//                // 单独拍照
//                getBitmapFromCamera();
//            }
        }

    };

    public void showPublishDialog() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }

            String[] permissions2 = {Manifest.permission.INTERNET,Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.ACCESS_WIFI_STATE};
            //验证是否许可权限
            for (String str : permissions2) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions2, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        getBitmapFromGallery();

    }
    /**相册**/
    private void getBitmapFromGallery() {
        // 相册
        PictureSelector.create(OrderRemakeMarketActivity.this)
                .openGallery(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
//                .theme(themeId)// 主题样式设置 具体参考 values/styles
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(5)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
//                .previewVideo(cb_preview_video.isChecked())// 是否可预览视频
//                .enablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .compressQuality(60)
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls(cb_hide.isChecked() ? false : true)// 是否显示uCrop工具栏，默认不显示
//                .isGif(cb_isGif.isChecked())// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认为100
                .minimumCompressSize(1000)// 小于1000kb的图片不压缩
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                //.rotateEnabled() // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.videoQuality()// 视频录制质量 0 or 1
                //.videoSecond()////显示多少秒以内的视频or音频也可适用
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    upfiles.clear();
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                    }

//                        adapter.setList(selectList);
//                        adapter.notifyDataSetChanged();
                    dataBean.getCartInfo().get(currentPosition).setSelectList(selectList);
                    if (currentPosition==0){//更新第一个条目的选择图片路径
                        cartInfoSave.get(0).setSelectList(selectList);
                    }
                    remakeGoodsAdapter.setData(currentPosition,dataBean.getCartInfo().get(currentPosition));
                    upload();
                    break;
            }
        }
    }

    //检查提交按钮状态
    private void checkBtnState() {
            //三个评星都选了按钮黄色
            if (quality!=0&&packing!=0){
                tv_submit.setBackgroundResource(R.drawable.dfb9129_bg_r3);
            }
    }

    /**上传多张图片*/
    private void uploadImg(File file, String fileName) {

        try{
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
            MultipartBody.Part part = MultipartBody.Part.createFormData("file[]", fileName+".jpg", RequestBody.create(MediaType.parse("image/jpg"), file));
            upfiles.add(part);

        }catch (Exception e){
            ToastUtils.s(this,"当前网络状态不佳，上传失败，请稍后再试");
        }

    }

    /**
     * 添加软键盘监听
     */
    private void setSoftKeyBoardListener() {
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(this);
        //软键盘状态监听
        softKeyBoardListener.setListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘已经显示，做逻辑

            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘已经隐藏,做逻辑
                rl_top.requestFocus();
                rl_top.setFocusable(true);
                rl_top.setFocusableInTouchMode(true);
            }
        });
    }
}
